package com.ruoyi.apartments.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OSSUtils {

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.access-key}")
    private String accessKeyId;

    @Value("${spring.cloud.alicloud.oss.secret-key}")
    private String accessKeySecret;

    @Value("${spring.cloud.alicloud.oss.bucket-name}")
    private String bucketName;

    @Value("${spring.cloud.alicloud.oss.base-path}")
    private String basePath;

    /**
     * 上传文件到OSS
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 生成唯一文件名（避免重复）
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String filePath = basePath + fileName;

            // 上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, file.getInputStream());
            ossClient.putObject(putObjectRequest);

            // 返回文件访问URL
            return "https://" + bucketName + "." + endpoint + "/" + filePath;
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }

    public void deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return;
        }

        // 解析文件路径
        String filePath = fileUrl.substring(fileUrl.indexOf(basePath));

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucketName, filePath);
        } finally {
            ossClient.shutdown();
        }
    }

}
